package outputter;

import java.util.ArrayList;
import java.util.Iterator;

import org.slf4j.Logger;

import common.Log;

import main.run.MainThread;

public class Outputter extends Thread {
	private long startWait = System.currentTimeMillis();
	private ArrayList<String> lstOut = new ArrayList<>();
	private Logger logErr = Log.logErr();
	@Override
	public void run() {
		try {
			while (true) {
				synchronized (MainThread.qOutput) {
					if (MainThread.qOutput.size() >= 200) {
						while (MainThread.qOutput.size() >= 200) {
							Iterator<String> ite = MainThread.qOutput
									.iterator();
							while (ite.hasNext()) {
								if (lstOut.size() >= 200) {
									break;
								}
								String value = ite.next();
								lstOut.add(value);
							}
							WriteResult.writefile(lstOut);
							for (int i = 0; i < lstOut.size(); i++) {
								String value = lstOut.get(i);
								MainThread.qOutput.remove(value);
							}
							lstOut.clear();
						}
						startWait = System.currentTimeMillis();
					} else if (System.currentTimeMillis() - startWait >= 60000) {
						Iterator<String> ite = MainThread.qOutput
								.iterator();
						while (ite.hasNext()) {
							String value = ite.next();
							lstOut.add(value);
						}
						WriteResult.writefile(lstOut);
						for (int i = 0; i < lstOut.size(); i++) {
							String value = lstOut.get(i);
							MainThread.qOutput.remove(value);
						}
						startWait = System.currentTimeMillis();
					}
//					MainThread.qOutput.wait(600);
//					MainThread.qOutput.notifyAll();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logErr.error(e.toString());
		}
		super.run();
	}
}
